package app.search.client;


import app.search.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.Window;

import com.google.gwt.maps.client.Maps;
import com.google.gwt.maps.client.InfoWindow;
import com.google.gwt.maps.client.InfoWindowContent;
import com.google.gwt.maps.client.InfoWindowContent.InfoWindowTab;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.event.MarkerClickHandler;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.geom.LatLngBounds;
import com.google.gwt.maps.client.overlay.Marker;

import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.Layout;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;
import com.smartgwt.client.widgets.tab.events.TabSelectedEvent;
import com.smartgwt.client.widgets.tab.events.TabSelectedHandler;
import com.smartgwt.client.widgets.tree.events.LeafClickEvent;
import com.smartgwt.client.widgets.tree.events.LeafClickHandler;
import com.smartgwt.client.widgets.tree.TreeNode;

import com.smartgwt.client.data.Record;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import com.smartgwt.client.widgets.grid.events.RecordDoubleClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordDoubleClickHandler;
import com.smartgwt.client.widgets.grid.events.RowContextClickEvent;
import com.smartgwt.client.widgets.grid.events.RowContextClickHandler;

import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.util.SC;

import com.smartgwt.client.widgets.Label;


import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;
import com.smartgwt.client.widgets.ImgButton;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;

import com.smartgwt.client.widgets.layout.VLayout;

import com.bramosystems.oss.player.youtube.client.YouTubePlayer;


//import com.google.gwt.event.dom.client.ClickEvent;
//import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.maps.client.InfoWindow;
import com.google.gwt.maps.client.InfoWindowContent;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.geocode.Geocoder;
import com.google.gwt.maps.client.geocode.LatLngCallback;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
//import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;

import app.search.client.GridExpansionComponent;

import com.google.gwt.maps.client.overlay.Icon;
import com.google.gwt.maps.client.overlay.MarkerOptions;
import com.google.gwt.maps.client.geom.Point;
import com.google.gwt.maps.client.geom.Size;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;

import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.DockLayoutPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Search implements EntryPoint, HistoryListener {

        private TabSet mainTabSet;
        //private SideNavTree sideNav;
        private ClassGrid classGrid;
        private MapWidget map;
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {

        DeferredCommand.add(new Command() {
          public void execute() {


          }
        });

        final String initToken = History.getToken();

        if (!Maps.isLoaded()) {
          Window.alert("The Maps API is not installed."
              + "  The <script> tag that loads the Maps API may be missing or your Maps key may be wrong.");
          return;
        }

        if (!Maps.isBrowserCompatible()) {
          Window.alert("The Maps API is not compatible with this browser.");
          return;
        }



        //setup overall layout / viewport
        VLayout main = new VLayout() {
            @Override
            protected void onInit() {
                super.onInit();
                if (initToken.length() != 0) {
                    onHistoryChanged(initToken);
                }
            }
        };

        ToolStrip topBar = new ToolStrip();
        topBar.setHeight(33);
        topBar.setWidth100();

        topBar.addSpacer(6);
        ImgButton sgwtTopButton = new ImgButton();
        sgwtTopButton.setSrc("pieces/24/cube_green.png");
        sgwtTopButton.setWidth(24);
        sgwtTopButton.setHeight(24);
        sgwtTopButton.setPrompt("Class Search");
        sgwtTopButton.setHoverStyle("interactImageHover");
        sgwtTopButton.setShowRollOver(false);
        sgwtTopButton.setShowDownIcon(false);
        sgwtTopButton.setShowDown(false);
        sgwtTopButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
            public void onClick(ClickEvent event) {
                com.google.gwt.user.client.Window.open("http://code.google.com/p/smartgwt/", "sgwt", null);
            }
        });
        topBar.addMember(sgwtTopButton);
        topBar.addSpacer(6);

        Label title = new Label("YCOA Locations");
        title.setStyleName("sgwtTitle");
        title.setWidth(300);
        topBar.addMember(title);

        topBar.addFill();

        mainTabSet = new TabSet();


        VLayout sideNavLayout = new VLayout();
        sideNavLayout.setHeight100();
        //sideNavLayout.setWidth(185);
        sideNavLayout.setWidth(385);
        sideNavLayout.setShowResizeBar(true);


        classGrid = new ClassGrid(mainTabSet);
        classGrid.setSize("100%", "100%");
        classGrid.addRecordClickHandler(new RecordClickHandler() {
          public void onRecordClick(RecordClickEvent event) {
            //detailViewer.setData(countryGrid.getSelection());
            //final String address = "10 10th Street, Atlanta, GA";
            StringBuffer sb = new StringBuffer();
	    //ListGridRecord record = event.getRecord();
	    final Record record = (Record)event.getRecord();
            sb.append("" 
               + record.getAttributeAsString("address") 
               + " "
               + record.getAttributeAsString("city") 
               + ", "
               + record.getAttributeAsString("state") 
               + " "
               + record.getAttributeAsString("zip") 
               + "");
	    final String address = sb.toString();
            Geocoder geocoder = new Geocoder();
            geocoder.getLatLng(address, new LatLngCallback() {
              public void onFailure() {
              }
              public void onSuccess(LatLng point) {
	       try {
                // Create our "tiny" marker icon
                Icon icon = Icon.newInstance("/images/sports/16/pawn_Soccer.png");
                icon.setShadowURL("http://labs.google.com/ridefinder/images/mm_20_shadow.png");
                icon.setIconSize(Size.newInstance(16, 16));
                icon.setShadowSize(Size.newInstance(22, 20));
                icon.setIconAnchor(Point.newInstance(6, 20));
                icon.setInfoWindowAnchor(Point.newInstance(5, 1));
                MarkerOptions markerOptions = MarkerOptions.newInstance();
                markerOptions.setIcon(icon);
	         YouTubePlayer youTubePlayer = new YouTubePlayer("http://www.youtube.com/v/07QOTxvg2xc", "300px", "300px");
	       //final String videoString = "<object width=\"300\" height=\"300\"><param name=\"movie\" value=\"http://www.youtube.com/v/07QOTxvg2xc?fs=1&amp;hl=en_US\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://www.youtube.com/v/07QOTxvg2xc?fs=1&amp;hl=en_US\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"300\" height=\"300\"></embed></object>";
                final String facebookLikeBox = "<iframe src=\"http://www.facebook.com/plugins/livefeed.php?app_id=114447358569254&amp;width=300&amp;height=300\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:300px; height:300;\" allowTransparency=\"true\"></iframe>";
                InfoWindow info = map.getInfoWindow();
                map.setCenter(point, 13);
                Marker marker = new Marker(point, markerOptions);
                map.addOverlay(marker);
                //info.open(marker, new InfoWindowContent(address));
                GridExpansionComponent expansion = new GridExpansionComponent(record, mainTabSet);
                InfoWindowTab tabs[] = new InfoWindowTab[3];
                VerticalPanel panel = new VerticalPanel();
                panel.add(expansion);
                tabs[0] = new InfoWindowTab("Info", panel);
                //tabs[1] = new InfoWindowTab("Video", videoString);
                tabs[1] = new InfoWindowTab("Video", youTubePlayer);
                tabs[2] = new InfoWindowTab("Facebook", facebookLikeBox);
                final InfoWindowContent content = new InfoWindowContent(tabs, 0);
                info.open(map.getCenter(), content);
	       } catch(Exception e) {
		 e.printStackTrace();
	       }
               mainTabSet.selectTab("map");
              }
            });
          }
        });
        sideNavLayout.addMember(classGrid);

/*
        sideNav = new SideNavTree();
        sideNav.addLeafClickHandler(new LeafClickHandler() {
            public void onLeafClick(LeafClickEvent event) {
                TreeNode node = event.getLeaf();
                //showSample(node);
            }
        });
        sideNavLayout.addMember(sideNav);
*/

        Canvas canvas = new Canvas();
        canvas.setBackgroundImage("[SKIN]/shared/background.gif");
        canvas.setWidth100();
        canvas.setHeight100();
        canvas.addChild(mainTabSet);

        Tab tab = new Tab();
        Canvas mapPanel = new Canvas();
        mapPanel.setSize("100%", "100%");
        mapPanel.setWidth100();
        mapPanel.setHeight100();
        map = new MapWidget(LatLng.newInstance(37.4419, -122.1419), 13);
        map.setVisible(false);
        tab.setID("map");
        tab.setTitle("Map&nbsp;&nbsp;");
        tab.setIcon("pieces/16/cube_green.png");
        tab.setWidth(80);
        HLayout mainPanel = new HLayout();
        mainPanel.setHeight100();
        mainPanel.setWidth100();
        tab.setPane(mainPanel);
        mainTabSet.addTab(tab);
        Layout paneContainerProperties = new Layout();
        paneContainerProperties.setLayoutMargin(0);
        paneContainerProperties.setLayoutTopMargin(1);
        mainTabSet.setPaneContainerProperties(paneContainerProperties);
        mainTabSet.setWidth100();
        mainTabSet.setHeight100();
        mainTabSet.addTabSelectedHandler(new TabSelectedHandler() {
            public void onTabSelected(TabSelectedEvent event) {
                onWindowResized(Window.getClientWidth(), Window.getClientHeight()); 
                Tab selectedTab = event.getTab();
                String historyToken = selectedTab.getAttribute("historyToken");
                if (historyToken != null) {
                    History.newItem(historyToken, false);
                } else {
                    History.newItem("main", false);
                }
            }
        });

        map.setUIToDefault();
        map.setHeight("550px");
        map.setWidth("800px");
        mapPanel.addChild(map);
        tab.setPane(mapPanel);
        map.checkResizeAndCenter();
        map.setVisible(true);

        main.addMember(topBar);
        main.setWidth100();
        main.setHeight100();
        main.setStyleName("tabSetContainer");

        HLayout hLayout = new HLayout();
        hLayout.setLayoutMargin(5);
        hLayout.setWidth100();
        hLayout.setHeight100();
        hLayout.addMember(sideNavLayout);
        hLayout.addMember(canvas);
        main.addMember(hLayout);

        main.draw();

	classGrid.getGroupTree().openAll();

    }

    public void onWindowResized(int width, int height) {
      int tabBarAbsoluteLeft = mainTabSet.getAbsoluteLeft();
      int tabBarAbsoluteTop = mainTabSet.getAbsoluteTop();
      int tabBarOffsetHeight = mainTabSet.getOffsetHeight();
      map.setWidth(Integer.toString(width-tabBarAbsoluteLeft-20));
      map.setHeight(Integer.toString(height-tabBarAbsoluteTop-tabBarOffsetHeight-20));
    } 

    public void onHistoryChanged(String historyToken) {
        if (historyToken == null || historyToken.equals("")) {
            mainTabSet.selectTab(0);
        } else {
	 /*
            ExplorerTreeNode[] showcaseData = sideNav.getShowcaseData();
            for (ExplorerTreeNode explorerTreeNode : showcaseData) {
                if (explorerTreeNode.getNodeID().equals(historyToken)) {
                    showSample(explorerTreeNode);
                    sideNav.selectRecord(explorerTreeNode);
                    Tree tree = sideNav.getData();
                    TreeNode categoryNode = tree.getParent(explorerTreeNode);
                    while (categoryNode != null && !"/".equals(tree.getName(categoryNode))) {
                        tree.openFolder(categoryNode);
                        categoryNode = tree.getParent(categoryNode);
                    }
                }
            }
	 */
        }
    }

}
